package com.security.open.common.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mvc.entity.base.Pager;
import com.mvc.entity.base.Param;
import com.mvc.entity.base.Result;
import com.mvc.enums.Code;
import com.mvc.web.IController;
import com.utils.util.Dates;
import com.utils.util.Maps;
import com.utils.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * 测试接口
 *
 *
 * @author 谢长春 on 2017-9-18
 */
@RequestMapping("/open/test/{version}")
@Controller
@Slf4j
public class OpenTestController implements IController<String> {

    @GetMapping("/thymeleaf")
    public String thymeleaf(ModelMap model) {
        model.addAttribute("id", Util.uuid());
        model.addAttribute("name", "JX");
        model.addAttribute("timestamp", Dates.now().formatDateTime());
        return "/static/html/thymeleaf";
    }

    /**
     * 获取所有响应码
     * URL:/open/test
     * 参数：
     *
     * @return Result
     */
    @GetMapping("/codes")
    @ResponseBody
    public Result<?> codes(@PathVariable final int version) {
        final JSONObject obj = new JSONObject(true);
        for (Code code : Code.values()) {
            obj.put(code.name(), code.comment);
        }
        return new Result<>().setSuccess(obj);
    }

    /**
     * 保存
     * URL:/open/test
     * 参数：param=JSONObject
     *
     * @param param Param 参数对象
     * @return Result<E>
     */
    @PostMapping
    @ResponseBody
    @Override
    public Result<Object> save(
            @PathVariable final int version,
            @RequestBody(required = false) Param param) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Param.of(param).parseObject())
                    .setExtras(Param.of(param).parseObject())
                    .setException("参数解析成功，在data和extras都反回了参数")
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * 修改数据
     * URL:/open/test/{id}
     * 参数：param=JSONObject
     *
     * @param id     String 数据ID
     * @param param Param 参数对象
     * @return Result<E>
     */
    @PutMapping("/{id}")
    @ResponseBody
    @Override
    public Result<Object> update(
            @PathVariable final int version,
            @PathVariable final String id,
            @RequestBody(required = false) Param param) {
        final Result<Object> result = new Result<>();
        try {
            JSONObject obj = Param.of(param).parseObject();
            obj.put("id", id);
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(obj)
                    .setExtras(JSON.parseObject(obj.toJSONString()))
                    .setException("参数解析成功，在data和extras都反回了参数，数据ID：" + id)
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * 按ID删除，物理删除
     * URL:/open/test/{id}
     * 参数：{id}数据ID；
     *
     * @param id String  数据ID
     * @return Result<Object>
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    @Override
    public Result<Object> deleteById(
            @PathVariable final int version,
            @PathVariable final String id) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                    .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                    .setException(String.format("物理删除ID为【%s】的数据", id))
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * 测试 patch 带参数
     * URL:/open/test/change/{id}
     * 参数：{id}数据ID；
     *
     * @param id String 数据ID
     * @return Result<Object>
     */
    @PatchMapping("/change/{id}")
    @ResponseBody
    public Result<Object> updateById(@PathVariable final int version, @PathVariable final String id, @RequestBody(required = false) Param param) {
        return update(version, id, param);
    }

    /**
     * 按ID删除，逻辑删除
     * URL:/open/test/{id}
     * 参数：{id}数据ID；
     *
     * @param id String 数据ID
     * @return Result<Object>
     */
    @PatchMapping("/{id}")
    @ResponseBody
    @Override
    public Result<Object> markDeleteById(
            @PathVariable final int version,
            @PathVariable final String id) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                    .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                    .setException(String.format("逻辑删除ID为【%s】的数据", id))
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * 批量操作按ID删除，逻辑删除
     * URL:/open/test
     * 参数：param=JSONObject
     *
     * @param param Param 参数对象
     * @return Result<Object>
     */
    @PatchMapping
    @ResponseBody
    @Override
    public Result<Object> markDelete(
            @PathVariable final int version,
            @RequestBody(required = false) Param param) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Maps.of(String.class, JSONArray.class).put("ids", Param.of(param).hasArray().parseArray()).buildJSONObject())
                    .setExtras(Maps.of(String.class, JSONArray.class).put("ids", Param.of(param).hasArray().parseArray()).buildJSONObject())
                    .setException(String.format("批量逻辑删除ID为【%s】的数据", String.join(",", Param.of(param).hasArray().parseArray(String.class))))
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * 按ID查询
     * URL:/open/test/{id}
     * 参数：{id}数据ID；
     *
     * @param id 数据ID
     * @return Result<E>
     */
    @GetMapping("/{id}")
    @ResponseBody
    @Override
    public Result<Object> findById(
            @PathVariable final int version,
            @PathVariable final String id) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Maps.ofSS().put("id", id).buildJSONObject())
                    .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
                    .setException(String.format("查询ID为【%s】的数据", id))
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    @GetMapping
    @ResponseBody
    @Override
    public Result<Object> search(
            @PathVariable final int version,
            @RequestParam(required = false, defaultValue = "{}") final String json) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Param.of(json).parseObject())
                    .setExtras(Param.of(json).parseObject())
                    .setException("带参查询集合，不分页")
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    @GetMapping("/{number}/{size}")
    @ResponseBody
    @Override
    public Result<Object> page(

            @PathVariable final int version,
            @PathVariable final int number,
            @PathVariable final int size,
            @RequestParam(required = false, defaultValue = "{}") final String json
    ) {
        final Result<Object> result = new Result<>();
        try {
            result
                    .setCode(Code.SUCCESS) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                    .setSuccess(Param.of(json).parseObject())
                    .setExtras(JSON.parseObject(Pager.builder().number(number).size(size).build().toString()))
                    .setException("带参 + 分页查询集合")
            ;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setException(e);
        }
        return result;
    }

    /**
     * URL:/open/test/application/xml
     * 参数：
     *
     * @return Result<E>
     */
    @GetMapping(value = "/application/xml", produces = {"application/xml"})
    @ResponseBody
    public String getApplicationXml() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header>表头</header><body><row><cell>第一列</cell><cell>第二列</cell></row><row><cell>第一列</cell><cell>第二列</cell></row></body></table>";
    }

    /**
     * URL:/open/test/text/xml
     * 参数：
     *
     * @return Result<E>
     */
    @GetMapping(value = "/text/xml", produces = {"text/xml"})
    @ResponseBody
    public String getTextXml() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header><cell>第一列</cell><cell>第二列</cell></header><body><row><cell>第一行-第一列</cell><cell>第一行-第二列</cell></row><row><cell>第二行-第一列</cell><cell>第二行-第二列</cell></row></body></table>";
    }

    /**
     * URL:/open/test/text/html
     * 参数：
     *
     * @return Result<E>
     */
    @GetMapping(value = "/text/html", produces = {"text/html"})
    @ResponseBody
    public String getTextHtml() {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>账号激活</title>\n" +
                "</head>\n" +
                "<body style=\"font-family: 'Microsoft Himalaya'\">\n" +
                "<h3>游客，你好：</h3>\n" +
                "<p style=\"text-indent: 2em;\">\n" +
                "    点击<a href=\"http://beta.mvc.com\" target=\"_blank\"><b>【激活账号】</b></a>，或复制以下链接在浏览器激活：<br>\n" +
                "    http://beta.mvc.com\n" +
                "</p>\n" +
                "<h4 style=\"text-align: right;padding-right: 100px\">\n" +
                "   xx团队\n" +
                "</h4>\n" +
                "</body>\n" +
                "</html>";
    }

    /**
     * URL:/open/test/redirect
     * 参数：
     *
     * @return Result<E>
     */
    @GetMapping(value = "/redirect", produces = {"text/html"})
    public String toHome() {
        return "redirect:http://beta.mvc.com";
    }


//    @Autowired
//    private UserRepository userRepository;
//
//    @PreAuthorize("hasRole('ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public List<TabUser> getUsers(){
//        return userRepository.findAll();
//    }
//
//    @PreAuthorize("hasRole('ADMIN')")
//    @PostMapping
//    @ResponseBody
//    TabUser addUser(@RequestBody TabUser user){
//        TabUser user1 = userRepository.save(user);
//        return user1;
//    }
//
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ADMIN')")
//    @GetMapping("/{id}")
//    @ResponseBody
//    public TabUser getUser(@PathVariable String id){
//        return userRepository.findById(id).orElse(null);
//    }
//
//
//    //更新
//    @PreAuthorize("hasRole('ADMIN')")
//    @PutMapping("/{id}")
//    @ResponseBody
//    public TabUser updateUser(@PathVariable String id, @RequestBody TabUser updateUser){
//        updateUser.setId(id);
//        //save方法有则更新无则添加
//        return userRepository.save(updateUser);
//    }
//
//    @PreAuthorize("hasRole('ADMIN')")
//    @DeleteMapping("/{id}")
//    @ResponseBody
//    public TabUser deleteUser(@PathVariable String id){
//        TabUser deleteUser = userRepository.findById(id).orElse(null);
//        userRepository.deleteById(id);
//        return deleteUser;
//    }
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ROLE_ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public TabUser findByUsername(@RequestParam(value = "username") String username){
//        return userRepository.findByUsernameOrPhone(username,username);
//    }
//
//    @RequestMapping("/auto")
//    @ResponseBody
//    public Page<TabUser> auto(TabUser user){
////        Pager<TabUser> users = userRepository.findByAutoLike(user, new PageRequest(0, 10));
////        return users;
//        return null;
//    }
}